<script setup>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
import { ref, watch } from 'vue';

// 进入页面读取初始值，注意兼容处理
const arr = JSON.parse(localStorage.getItem('list')) || [
  {
    id: 1,
    name: '吃饭',
    done: true,
  },
  {
    id: 2,
    name: '睡觉',
    done: false,
  },
  {
    id: 3,
    name: '打豆豆',
    done: false,
  },
]

const list = ref(arr)
// 数据持久化
watch(list, () => {
  localStorage.setItem('list', JSON.stringify(list.value))
}, { deep: true })

// 修改状态
const change = (id) => {
  // console.log('id -----> ', id);
  const obj = list.value.find(v => v.id === id)
  obj.done = !obj.done
}

// 删除
const del = (id) => {
  // 写法1,splice(索引,1)
  // const index = list.value.findIndex(v => v.id === id)
  // list.value.splice(index, 1)

  // 写法2，filter
  list.value = list.value.filter(v => v.id !== id)
}

// 添加功能
const add = (name) => {
  // console.log('name -----> ', name);
  list.value.unshift({
    id: +new Date(),
    name,
    done: false
  })
}

// 全选反选
const changeAll = (bl) => {
  list.value.forEach(v => v.done = bl)
}

</script>

<template>
  <section class="todoapp">
    <TodoHeader @add="add"></TodoHeader>
    <TodoMain :list="list" @change="change" @del="del" @changeAll="changeAll"></TodoMain>
    <TodoFooter :list="list"></TodoFooter>
  </section>
</template>

<style>

</style>
